package org.example.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.constant.JwtClaimsConstant;
import org.example.constant.MessageConstant;
import org.example.dao.entity.Users;
import org.example.dto.req.*;
import org.example.dto.resp.UserLoginVO;
import org.example.dto.resp.UserPageVO;
import org.example.dto.resp.UserVO;
import org.example.feign.PermissionServiceFeignClient;
import org.example.mq.LogProduct;
import org.example.properties.JwtProperties;
import org.example.result.Result;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private LogProduct logProduct;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private PermissionServiceFeignClient permissionServiceFeignClient;


    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterReqDTO reqDTO, HttpServletRequest request) {
        log.info("用户注册：{}", reqDTO);
        return userService.createUser(reqDTO, request);
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginReqDTO reqDTO, HttpServletRequest request) {
        log.info("用户登录：{}", reqDTO);

        Users users = userService.login(reqDTO, request);

        //登录成功
        //开始创建jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, users.getUserId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        log.info("用户[{}]登录成功，生成令牌:[{}]", reqDTO.getUserName(), token);

        UserLoginVO userLoginVo = UserLoginVO.builder()
                .id(users.getUserId())
                .userName(users.getUserName())
                .token(token)
                .build();

        return Result.success(MessageConstant.LOGIN_SUCCESS, userLoginVo);
    }

    /**
     * 分页查询
     *
     * @param reqDTO
     * @return
     */
    @GetMapping("/users")
    public Result<UserPageVO> page(@RequestBody UserPageQueryReqDTO reqDTO, HttpServletRequest request) {

        log.info("员工分页查询，参数为：{}", reqDTO);
        UserPageVO users = userService.pagequery(reqDTO, request);
        return Result.success(MessageConstant.QUERY_SUCCESS, users);
    }

    /**
     * 根据id查询用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public Result<UserVO> getById(@PathVariable BigInteger userId, HttpServletRequest request) {
        log.info("查询员工，id为：{}", userId);
        UserVO userVO = userService.getUserInfoById(userId, request);
        return Result.success(MessageConstant.QUERY_SUCCESS, userVO);
    }

    /**
     * 修改用户信息
     *
     * @param userId
     * @param user
     * @return
     */
    @PutMapping("/{userId}")
    public Result update(@PathVariable BigInteger userId, @RequestBody UserDTO user, HttpServletRequest request) {
        try {
            log.info("更新员工，数据为：{}", user);
            userService.updateById(userId, user, request);
            return Result.success(MessageConstant.UPDATE_SUCCESS);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 重置密码
     *
     * @param reqDTO
     * @return
     */
    @PostMapping("/reset-password")
    public Result resetPassword(@RequestBody ResetPasswordDTO reqDTO, HttpServletRequest request) {

        log.info("密码重置，参数为：{}", reqDTO);
        userService.resetPassword(reqDTO, request);
        return Result.success(MessageConstant.PASSWORD_RESET_SUCCESS);
    }

    //级联删除用户
    @DeleteMapping("/{userId}")
    public Result delete(@PathVariable BigInteger userId, HttpServletRequest request) {
        log.info("删除用户，id为：{}", userId);
        userService.deleteById(userId, request);
        return Result.success(MessageConstant.DELETE_SUCCESS);
    }

    //超管：升级用户为管理员
    @PostMapping("/upAdmin")
    public Result upAdminById(@RequestParam BigInteger userId, HttpServletRequest request) {
        log.info("升级用户为管理员，id为：{}", userId);
        return userService.upgradeToAdmin(userId, request);
    }

    //超管：降级用户为普通用户
    @PostMapping("/downUser")
    public Result downUserById(@RequestParam BigInteger userId, HttpServletRequest request) {
        log.info("降级用户为普通用户，id为：{}", userId);
        return userService.downgradeToUser(userId, request);
    }
}